<template>
  <div
    class="flex-container"
    v-loading="loading"
    element-loading-text="正在注册中，请稍后....."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="login_panel card">
      <div class="loginTitle">
        <!-- 注册账号 -->
        <h2>{{ $t('reg.title') }}</h2>
      </div>
      <div class="login_form">
        <el-form
          :model="loginForm"
          :rules="rules"
          status-icon
          ref="loginForm"
          label-width="100px"
          class="form_panel"
        >
          <div class="el-item">
            <el-form-item prop="username">
              <el-input
                type="text"
                v-model="loginForm.username"
                autocomplete="off"
                :placeholder="$t('reg.username')"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-s-custom"></i>
              </el-input>
            </el-form-item>
          </div>
          <div class="el-item">
            <el-form-item prop="user_email">
              <el-input
                type="email"
                v-model="loginForm.user_email"
                autocomplete="off"
                :placeholder="$t('reg.email')"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-message"></i>
              </el-input>
            </el-form-item>
          </div>
          <div class="el-item">
            <el-form-item prop="user_password">
              <el-input
                type="password"
                v-model="loginForm.user_pass"
                autocomplete="off"
                :placeholder="$t('reg.pass')"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-lock"></i>
              </el-input>
            </el-form-item>
          </div>
          <div class="el-item">
            <el-form-item prop="checkPass">
              <el-input
                type="password"
                v-model="loginForm.checkPass"
                autocomplete="off"
                :placeholder="$t('reg.checkpass')"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-lock"></i>
              </el-input>
            </el-form-item>
          </div>
          <!-- 邀请码 -->
          <div class="el-item item_code">
            <el-form-item prop="invite_code">
              <el-input
                class="code"
                type="text"
                v-model="loginForm.code_string"
                autocomplete="off"
                :placeholder="$t('reg.valicode')"
                clearable
              >
                <i slot="prefix" class="el-input__icon el-icon-tickets"></i>
              </el-input>
              <el-button
                type="primary"
                class="code_btn"
                :disabled="isSendCodeButtonVisible"
                @click="sendCode"
                >{{ sendCodeButtnonText }}</el-button
              >
            </el-form-item>
          </div>
          <div class="el-item el-login-btn-panel">
            <div>
              <!-- 注册按钮 -->
              <el-button
                type="primary"
                class="buttonWidth"
                @click="RegUser('loginForm')"
                >{{$t('reg.btn')}}</el-button
              >
            </div>
          </div>
          <div class="loginBottom back_link">
            <!-- 返回登录页面 -->
            <router-link to="/login">{{$t('reg.backloginlink')}}</router-link>
          </div>
        </el-form>
      </div>
    </div>
    <!-- 成功提示 -->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
      :show-close="false"
    >
      <span>注册成功,{{ count }}秒后自动跳转到登录页面！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="login()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import { sendRegCode,getGlobalLanguageByArea,regUser } from '@/api';

export default {
  name: "RegView",
  data() {
    // let _self = this;
    var validateUsername = (rule, value, callback) => {
      //以英文字母开头，只能包含英文字母、数字、下划线
      var regex = new RegExp(
        "^[a-zA-Z][a-zA-Z0-9_]*$"
      );
      
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (value.length < 3 || value.length > 16) {
        callback(new Error("请输入3~16位用户名"));
      } else if(!regex.test(value)){
        callback(new Error("必须英文字母开头，允许数字"));
      } else {
        setTimeout(() => {
          if (this.loginForm.username !== "") {
            //_self.$refs.loginForm.validateField("username");
          }
        }, 1000);
        callback();
      }
    }; //validateEmail
    var validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else {
        setTimeout(() => {
          if (this.loginForm.user_email !== "") {
            //_self.$refs.loginForm.validateField("user_email");
          }
        }, 2000);
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      //必须包含大小写字母、数字、特殊字符长度再9-16位之间
      var regex = new RegExp(
        "(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,16}"
      );

      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 8 || value.length > 16) {
        callback(new Error("请输入8~16位密码"));
      } else if (!regex.test(value)) {
        callback(
          new Error("密码必须同时包含字母、数字和特殊字符其中三项且至少8位")
        );
      } else {
        setTimeout(() => {
          if (this.loginForm.checkPass !== "") {
            //_self.$refs.loginForm.validateField("checkPass");
          }
        }, 1000);
        callback();
      }
    };
    var validateInviteCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        setTimeout(() => {
          if (this.loginForm.code_string !== "") {
            //_self.$refs.loginForm.validateField("invite_code");
          }
        }, 1000);
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.loginForm.user_pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        user_email: "",
        user_pass: "",
        checkPass: "",
        code_string: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        invite_code: [{ validator: validateInviteCode, trigger: "blur" }],
        user_email: [
          { validator: validateEmail, trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        user_pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
      count: 3, //倒计时跳转首页面
      centerDialogVisible: false,
      loading: false,
      sendCodeButtnonText: this.$t('reg.sendcode'),
      isSendCodeButtonVisible: false, //按钮可用
      timesCounts: 10, //倒计时发送验证码
      formData:{
        in_language:"zh-CN",
      },
    };
  },
  beforeDestroy() {
    //离开页面销毁监听快捷键
    clearInterval(this.codetimer);
    clearInterval(this.timer);
  },
  created(){
    this.initI18nData();
  },
  methods: {
    //初始化国际化
    async initI18nData(){
      this.formData.in_language = navigator.language;
      let res= await getGlobalLanguageByArea(this.formData);
      // console.log(res);
      if(res.state==200){
        this.$i18n.locale = res.data.in_language_file;
        localStorage.setItem('lang', res.data.in_language_file); 
        
      }else{
        this.$i18n.locale = 'zh';
        localStorage.setItem('lang', 'zh');
      }
      this.loadpage = true;
    },
    //发送验证码
    sendCode() {
      if (this.user_email == "") {
        this.$message.error("输入邮箱不能为空！");
        return;
      }
      this.timesCounts = 10;
      //设置按钮不可用
      this.isSendCodeButtonVisible = true;
      //开始调用倒计时
      this.SendTimer();
      //   this.codetimer();
      this.doSendCode();
    },
    async doSendCode() {
      //调用发送邮件
      let res = await sendRegCode({ user_email: this.loginForm.user_email });
      if (res.state == 200) {
        this.$message({
          message: "注册码已发送，请查收邮件！",
          type: "success",
        });
      }else{
        this.$message.error("验证码发送失败，请与管理员联系！");
      }
    },
    //倒计时 发送验证码第一中方法 setTimeout
    SendTimer() {
      let TIME_COUNT = this.timesCounts;
      if (this.timesCounts > 0 && this.timesCounts <= TIME_COUNT) {
        this.timesCounts--;
        this.sendCodeButtnonText = this.timesCounts + this.$t('reg.sec');
        // console.log(this.timesCounts);
      } else {
        this.isSendCodeButtonVisible = false;
        this.sendCodeButtnonText = this.$t('reg.sendcode');
        return;
      }

      setTimeout(() => {
        this.SendTimer();
      }, 1000);
    },
    //计时器自动保存(存在bug，调用第二次报错)
    codetimer() {
      const TIME_COUNT = this.timesCounts;
      this.codetimer = setInterval(() => {
        if (this.timesCounts > 0 && this.timesCounts <= TIME_COUNT) {
          this.timesCounts--;
          this.sendCodeButtnonText = +this.timesCounts + this.$t('reg.sec');
          console.log(this.timesCounts);
        } else {
          this.show = true;
          clearInterval(this.codetimer);
          this.codetimer = null;
        }
        if (this.timesCounts == 0) {
          //执行保存
          this.isSendCodeButtonVisible = false;
          this.sendCodeButtnonText = this.$t('reg.sendcode');
          clearInterval(this.codetimer);
          this.codetimer = null;
        }
      }, 1000);
    },
    //注册用户
    RegUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addUser();
        } else {
          return false;
        }
      });
    },
    async addUser() {
      this.loading = true;
      let res = await regUser(this.loginForm);
      if (res.state == 200) {
        this.centerDialogVisible = true;
        this.timer();
      } else {
        this.$message.error(res.message);
        this.loading = false;
      }
    },
    login() {
      this.$router.push("/login");
    },
    //倒计时
    timer() {
      const TIME_COUNT = this.count;
      this.timer = setInterval(() => {
        if (this.count > 0 && this.count <= TIME_COUNT) {
          this.count--;
        } else {
          this.show = true;
          clearInterval(this.timer);
          this.timer = null;
        }
        if (this.count == 0) {
          this.login();
          this.show = true;
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
  },
};
</script>
  <style scoped>
.flex-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: url("../assets/img/bg01.jpg") center center no-repeat;
  background-size: cover;
  height: 100vh;
}

.login_panel {
  width: 350px;
}

.card {
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.2509803922);
  -webkit-backdrop-filter: blur(10px);
  backdrop-filter: blur(10px);
  transform: scale(1);
  transition: all 0.3s;
}

.loginTitle {
  text-align: center;
  color: #fff;
  margin: 30px 0;
}

.login_form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form_panel {
  width: 90%;
}

.el-item {
  margin: 25px 0;
}

.buttonWidth {
  height: 42px;
  width: 100%;
  font-family: PingFangSC-Semibold;
  font-size: 18px;
  color: #ffffff;
  letter-spacing: 0;
  text-align: center;
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.loginBottom {
  margin-bottom: 30px;
  color: #ffffff;
}

.back_link a {
  font-size: 12px;
  color: #ffffff;
  text-decoration: none;
}
</style>
<style>
.el-form-item > div {
  margin-left: 0px !important;
}

.el-form-item .code {
  width: 180px;
  margin-right: 10px;
}

.el-form-item .code_btn {
  width: 120px;
}
</style>